<template>
  <div>
    <div>
      <we-button
        v-if="baseCode"
        @click="dialogFormVisible = true"
        type="primary"
        size="mini"
      >
        <em class="el-icon-plus"></em> 新增
      </we-button>
      <we-button
        v-if="baseCode"
        @click="detailRow(currentRow)"
        type="primary"
        size="mini"
      >
        <em class="el-icon-edit"></em> 修改
      </we-button>
      <we-button v-if="baseCode" @click="deleteRow" type="primary" size="mini">
        <em class="el-icon-delete"></em> 删除
      </we-button>
      <span v-if="baseName">当前人员：【 {{baseName}} 】</span>
    </div>

    <!-- 表格 -->
    <el-table
      size="mini"
      :header-cell-style="rowClass"
      :data="tableData"
      height="116px"
      border
      highlight-current-row
      resizable
      ref="singleTable"
      @row-dblclick="detailRow"
      @current-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column
        prop="designation_dictText"
        :show-overflow-tooltip="true"
        width="250"
        label="特殊专业技术人才称号"
      >
      </el-table-column>
      <el-table-column
        prop="getTime"
        :show-overflow-tooltip="true"
        width="200"
        label="获得时间"
      >
      </el-table-column>
      <el-table-column
        prop="conferNumber"
        :show-overflow-tooltip="true"
        width="230"
        label="授予文号"
      >
      </el-table-column>
      <el-table-column
        prop="conferCompany"
        :show-overflow-tooltip="true"
        label="授予单位"
      >
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <we-button @click="detailRow(scope.row)" type="primary" size="mini"
            >详情</we-button
          >
          <we-button @click="deleteRow(scope.row)" type="danger" size="mini">删除</we-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="table_tools">
      <we-pagination
        :total="pagination.total"
        :page="pagination.pageNum"
        :pageSize="pagination.pageSize"
        @currentChange="currentChange($event)"
      ></we-pagination>
    </div>
    <!-- 表格 -->

    <!-- 新增弹窗 -->
    <el-dialog
      title="特殊人才子集"
      :visible.sync="dialogFormVisible"
      @close="handleOffDialog"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="170px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="特殊专业技术人才称号" prop="designation">
              <el-cascader
                class="inputW"
                v-model="ruleForm.designation"
                :options="talentTitle"
                :props="{
                  expandTrigger: 'hover',
                  value: 'uuid',
                  label: 'name',
                  children: 'children',
                }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="获得时间" prop="getTime">
              <el-date-picker
                v-model="ruleForm.getTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授予文号" prop="conferNumber">
              <el-input
                class="inputW"
                v-model="ruleForm.conferNumber"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授予单位" prop="conferCompany">
              <el-input
                class="inputW"
                v-model="ruleForm.conferCompany"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <we-button size="mini" @click="handleOffDialog"
          >取 消</we-button
        >
        <we-button
          v-if="!isUpdate"
          size="mini"
          type="primary"
          @click="submitForm('ruleForm')"
          >新 增</we-button
        >
        <we-button
          v-if="isUpdate"
          size="mini"
          type="primary"
          @click="updateForm('ruleForm')"
          >修 改</we-button
        >
      </div>
    </el-dialog>
    <!-- 新增弹窗 -->
  </div>
</template>

<script>
import WeButton from "@/components/WeButton";
import WePagination from "@/components/WePagination";
import { parseTree } from "@/utils/util";
import {postAction, deleteAction, putAction, getAction} from "@/api/manage";
import {bus} from "@/utils/eventBus";
import {opDictNew} from "@/api/apiUrl";
export default {
  components: {
    WeButton,
    WePagination,
  },
  data() {
    return {
      isUpdate: false,
      pagination: {
        total: 10, // 总数据条数
        pageSize: 10, // 每页条数
        pageNum: 1, // 当前页
      }, // 列表分页数据
      tableData: [],
      dialogFormVisible: false,
      currentRow: null,
      ruleForm: {
        designation: "",
        getTime: "",
        conferNumber: "",
        conferCompany: "",
        uuidList:[],
      },
      rules: {
        designation: [
          {
            required: true,
            message: "请选择特殊专业技术人才称号",
            trigger: "change",
          },
        ],
        getTime: [
          { required: true, message: "请选择获得时间", trigger: "change" },
        ],
        conferNumber: [
          { required: true, message: "请填写授予文号", trigger: "blur" },
        ],
        conferCompany: [
          { required: true, message: "请填写授予单位", trigger: "blur" },
        ],
      },

      talentTitle: [], // 特殊专业技术人才称号
      baseCode: "",
      baseName: "",
    };
  },
  watch: {
    dialogFormVisible() {
      if (this.dialogFormVisible === false) {
        if (this.isUpdate) {
          setTimeout(() => {
            this.isUpdate = false;
            this.$store.commit("changeUpdateSubset", false);
            this.clearForm();
            if (this.$refs.ruleForm !== undefined) {
              this.$refs.ruleForm.resetFields();
            }
          }, 500);
        }
        if (this.$store.state.specialTalents === true) {
          this.$store.commit("changeSpecialTalents", false);
        }
      }
    },
    "$store.state.baseCode"(newval) {
      this.baseCode = newval;
      this.getList();
    },
    '$store.state.baseName'(newval) {
      this.baseName  = newval
    },
    "$store.state.specialTalents"(newval) {
      if (newval === true) {
        this.dialogFormVisible = true;
        if (this.$store.state.updateSubset === true) {
          this.isUpdate = true;
        } else {
          this.isUpdate = false;
        }
        this.baseCodes = this.$store.state.baseCodes;
        this.getTalentTitle();
      }
    },
  },
  methods: {
    clickSubset() {
      this.baseCode = this.$store.state.baseCode;
      this.getList();
      this.getTalentTitle();
    },
    batchAdd(data){
      this.dialogFormVisible = true
      this.ruleForm.uuidList = data
    },
    /*
     * 新增
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm));
          if (data.designation) {
            data.designation = data.designation.pop();
          }
          data.baseCode = this.baseCode;
          data.sysOrgCode = "测试部门";
          data.createUser = "测试员";
          if (this.$store.state.specialTalents === true) {
            for (let i = 0; i < this.baseCodes.length; i++) {
              data.baseCode = this.baseCodes[i];
              postAction("/specilProfessionalTeachPeople/add", data).then(
                (result) => {
                  if (result.code === 200) {
                    this.dialogFormVisible = false;
                    bus.$emit('handleDialog')
                    this.$message({
                      type: "success",
                      message: "新增成功!",
                    });
                    this.clearForm();
                  } else {
                    this.$message({
                      type: "waring",
                      message: result.msg,
                    });
                  }
                }
              );
            }
          } else {
            postAction("/specilProfessionalTeachPeople/add", data).then(
              (result) => {
                if (result.code === 200) {
                  this.dialogFormVisible = false;
                  bus.$emit('handleDialog')
                  this.getList();
                  this.$message({
                    type: "success",
                    message: "新增成功!",
                  });
                } else {
                  this.$message({
                    type: "waring",
                    message: result.msg,
                  });
                }
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    /**
     * 删除
     */
    deleteRow(row) {
      if (!this.currentRow) {
        this.$message("请选择要删除的数据！");
        return;
      }
      this.$confirm("是否要删除这条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAction("/specilProfessionalTeachPeople/delete", {
            uuids: [this.currentRow.uuid],
          }).then((res) => {
            if (res.code === 200) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "waring",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    /**
     * 修改
     */
    updateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm));
          if (typeof this.ruleForm.designation !== "string") {
            data.designation = data.designation.pop();
          }
          data.updateUser = "修改员";
          if (this.$store.state.updateSubset === true) {
            for (let i = 0; i < this.baseCodes.length; i++) {
              console.log(this.$store.state.getTableName);
            }
          } else {
            postAction("/specilProfessionalTeachPeople/update", data).then(
              (result) => {
                if (result.code === 200) {
                  this.dialogFormVisible = false;
                  bus.$emit('handleDialog')
                  this.getList();
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                } else {
                  this.$message({
                    type: "waring",
                    message: result.msg,
                  });
                }
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    handleOffDialog() {
      this.dialogFormVisible = false
      bus.$emit('handleDialog')
    },
    /**
     * 查询
     */
    getList() {
      let self = this;
      postAction("/specilProfessionalTeachPeople/pageList", {
        baseCode: this.baseCode,
        size: this.pagination.pageSize,
        page: this.pagination.pageNum,
      }).then((res) => {
        if (res.code === 200) {
          if (!res.data.list.length && self.pagination.pageNum !== 1) {
            self.pagination.pageNum -= 1;
            self.getList();
            return;
          }
          if (self.pagination.pageNum === 1 && res.data.list.length === 0) {
            self.pagination.total = 0;
          } else {
            self.pagination.total = res.data.total;
          }
          self.tableData = res.data.list;
        }
      });
    },

    /*
     * 查询特殊专业技术人才称号
     */
    getTalentTitle() {
      getAction(`${opDictNew.findTreeByType}?type=rs_cj`).then((result) => {
        if (result.code === 200) {
          this.talentTitle = result.data
        }
      });
    },

    /**
     * 详情
     */
    detailRow(row) {
      if (!row) {
        this.$message("请选择要编辑的数据！");
        return;
      }
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.isUpdate = true;
      this.dialogFormVisible = true;
    },

    // 当前页改变
    currentChange(event) {
      this.pagination.pageNum = event;
      this.getList();
    },

    /**
     * 清除form
     */
    clearForm() {
      this.ruleForm = {
        designation: "",
        getTime: "",
        conferNumber: "",
        conferCompany: "",
      };
    },

    rowClass({ row, rowIndex }) {
      return "background:rgba(248, 248, 249, 1);color:#000;";
    },
    handleChange() {},
    handleClose() {},
  },
};
</script>

<style scoped>
.table_tools {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
